<template>
	<cl-crud ref="crud" @load="onLoad" :on-refresh="onRefresh">
		<cl-pagefull>
			<template #head>
				<el-row type="flex">
					<cl-flex1>
						<cl-filter-group v-model="search">
							<cl-filter label="所属事业部">
								<cl-select
									v-model="search.biz_id"
									placeholder="请选择"
									filterable
									@change="changeBiz"
								>
									<el-option
										v-for="item in business"
										:key="item.biz_id"
										:label="item.biz_name"
										:value="item.biz_id"
									/>
								</cl-select>
							</cl-filter>
							<cl-filter label="分公司">
								<cl-select
									v-model="search.company_id"
									placeholder="请选择"
									filterable
									clearable
								>
									<el-option label="全部" value="" />
									<el-option
										v-for="item in bizRefData.company"
										:key="item.company_id"
										:label="item.company_name"
										:value="item.company_id"
									/>
								</cl-select>
							</cl-filter>
							<cl-filter label="品牌">
								<cl-select
									v-model="search.bra_id"
									placeholder="全部"
									filterable
									clearable
									style="width: 180px"
									multiple
									collapse-tags
								>
									<el-option
										v-for="item in bizRefData.brand"
										:key="item.bra_id"
										:label="item.bra_name"
										:value="item.bra_id"
									/>
								</cl-select>
							</cl-filter>
							<cl-filter label="预约城市">
								<cl-select
									v-model="search.city_id"
									placeholder="请选择"
									filterable
									clearable
									style="width: 150px"
								>
									<el-option label="全部" value="" />
									<el-option
										v-for="item in cityList"
										:key="item.id"
										:label="item.name"
										:value="item.id"
									/>
								</cl-select>
							</cl-filter>
							<cl-filter label="预约门店">
								<cl-select
									v-model="search.dept_id"
									multiple
									:multiple-limit="10"
									placeholder="全部"
									filterable
									clearable
									collapse-tags
								>
									<el-option
										v-for="item in bizRefData.shop_childs"
										:key="item.dept_id"
										:label="item.dept_name"
										:value="item.dept_id"
									/>
								</cl-select>
							</cl-filter>
							<cl-filter label="预约部门">
								<cl-cascader
									clearable
									v-model="search.appoint_dept_id"
									:options="preDeptList"
									:props="{
										value: 'dept_id',
										label: 'dept_name',
										checkStrictly: true
									}"
									filterable
									@change="changeAppointDept"
								/>
							</cl-filter>
							<cl-filter label="预约人员">
								<cl-select
									v-model="search.user_id"
									placeholder="请选择"
									filterable
									style="width: 150px"
									clearable
								>
									<el-option label="全部" value="" />
									<el-option
										v-for="item in userList"
										:key="item.user_id"
										:label="item.user_name"
										:value="item.user_id"
									/>
								</cl-select>
							</cl-filter>
							<cl-filter label="排店部门">
								<cl-cascader
									clearable
									v-model="search.after_dept_id"
									:options="afterDeptList"
									:props="{
										value: 'dept_id',
										label: 'dept_name'
									}"
									filterable
									style="width: 100%"
									@change="changeDept"
								/>
							</cl-filter>
							<cl-filter label="排店人员">
								<cl-select
									v-model="search.order_date_id_user"
									placeholder="请选择"
									clearable
									style="width: 100%"
								>
									<el-option
										v-for="item in afterUserList"
										:key="item.user_id"
										:label="item.user_name"
										:value="item.user_id"
									/>
								</cl-select>
							</cl-filter>
							<cl-filter label="客户关键字">
								<cl-keyword-search
									:value="{
										search_content: search.search_content,
										keyword_type: search.keyword_type
									}"
									@update="updateKeyword"
								/>

								<!-- <el-input
									v-model="search.search_content"
									placeholder="手机号/微信号/客户名称/会员号"
									clearable
									style="width: 220px"
								/> -->
							</cl-filter>
							<cl-filter label="预约类型">
								<cl-select v-model="search.cus_type" style="width: 140px">
									<el-option :value="0" label="全部" />
									<el-option :value="1" label="新客" />
									<el-option :value="2" label="老客" />
								</cl-select>
							</cl-filter>
							<cl-filter label="预约状态">
								<cl-select
									v-model="search.status"
									placeholder="请选择"
									filterable
									style="width: 140px"
									clearable
								>
									<el-option label="全部" value="" />
									<el-option
										v-for="item in statusData"
										:key="item.value"
										:label="item.label"
										:value="item.value"
									/>
								</cl-select>
							</cl-filter>
							<cl-filter label="是否待定">
								<cl-select v-model="search.is_undetermined" style="width: 140px">
									<el-option :value="1" label="是" />
									<el-option :value="2" label="否" />
								</cl-select>
							</cl-filter>
							<cl-filter label="预约时间" v-if="search.is_undetermined == 2">
								<cl-date-picker
									v-model="search.appoint_date"
									type="daterange"
									range-separator="至"
									start-placeholder="开始日期"
									end-placeholder="结束日期"
									value-format="yyyy-MM-dd"
									:clearable="false"
									style="width: 210px"
								/>
							</cl-filter>
						</cl-filter-group>
					</cl-flex1>
					<div>
						<el-button @click="exportExcel">
							<icon-svg name="icon-download-3" />
						</el-button>
						<el-button type="primary" @click="openAppointBoard">预约看板</el-button>
					</div>
					<!-- 财务报表-给财务导数据时使用 暂不删除 -->
					<!-- <div>
						<el-button @click="exportFinanceExcel()">
							<span>财务</span>
							<icon-svg name="icon-download-3" />
						</el-button>
					</div> -->
				</el-row>
			</template>
			<el-row>
				<!-- 数据表格 -->
				<cl-table v-bind="table" id="appointTable" ref="table">
					<cl-empty slot="empty" />
					<template #column-appoint_date="{ scope: { row } }">
						<div :class="{ 'is-pending': row.appoint_date == '待定时间' }">
							{{ row.appoint_date }}
						</div>
					</template>
					<template #column-customer="{ scope: { row } }">
						<cl-customer
							:gender="row.cus_sex"
							:name="row.cus_name"
							:cusId="row.cus_id+'' || '-'"
							:avatar="row.cus_img"
							:id_join_type="row.id_join_type"
						/>
					</template>
					<template #column-cus_type_dec="{ scope: { row } }">
						<div
							class="cus_type"
							:class="{
								'color-primary': row.cus_type == 1,
								old: row.cus_type == 2,
								'color-danger': row.cus_type == 3,
								'color-warning': row.cus_type == 4
							}"
						>
							{{ row.cus_type_dec }}
						</div>
					</template>
					<template #column-status="{ scope: { row } }">
						<div v-if="row.status == 5 && row.appoint_date != '-'">已超时</div>
						<div v-else>
							{{ row.status | constFilter("APPIONT_TYPE") }}
						</div>
					</template>
					<template #column-order_arrived="{ scope: { row } }">
						<div style="color: red;" v-if="row.order_user_arrived == 0">{{ row.order_arrived }}</div>
						<div v-else>
							{{ row.order_arrived }}
						</div>
					</template>
					<template #column-opt="{ scope: { row } }">
						<div class="flex flex-align-start">
							<el-button
								type="primary"
								v-auth="'store_appoint_edit'"
								v-if="![2, 4, 6, 7].includes(row.status)"
								@click="openAppoint(row)"
							>
								改约
							</el-button>
							<!-- <el-button type="primary" @click.stop="openDetail(row)"> {{ row.order_user_arrived == 0 ? `售中到店` : `取消到店` }} </el-button> -->
							<!-- <el-button
								@click.stop="openDetail(row)"
								v-auth="'store_cusdetailindex_look'"
							>
								详情
							</el-button> -->
							<el-button @click.stop="openDetail(row)"> 详情 </el-button>
							<el-button
								:type="row.order_user_arrived === 0 ? `danger` : ``"
								@click="arrived(row)"
								v-if="row.status == 1"
								>{{ row.order_user_arrived === 0 ? `客服到店` : `取消到店`}}</el-button
							>
						</div>
					</template>
				</cl-table>
			</el-row>
			<template #foot>
				<el-row type="flex">
					<cl-flex1 />
					<!-- 分页控件 -->
					<zm-pagination :props="{layout:'total,sizes, prev, pager, next'}" />
				</el-row>
			</template>
		</cl-pagefull>
		<!-- <cl-appoint-form ref="form" is-edit /> -->
		<modify-cart-time ref="modifyCartTime" @confirm="refresh"></modify-cart-time>
	</cl-crud>
</template>

<script>
import { mapState } from "vuex";
import constant from "@/constant";
import { exportExcelCoustom } from "@/utils/excel";
import { delEmptyChildren } from "@/utils";
import { last, cloneDeep } from "cl-admin/utils";
import dayjs from "dayjs";
import { constFilter as constFilterFn } from "@/filters";
import ModifyTime from "@/components/modify-cart/modify-time";

export default {
	name: "CusShopAppiont",
	inject: ["$layout"],
	components: {
		ModifyCartTime: ModifyTime
	},
	data() {
		return {
			cusTypeList: constant.CUS_TYPE,
			statusData: [
				{ label: "待服务", value: 1 },
				{ label: "已开单", value: 2 },
				{ label: "已流失", value: 7 },
				{ label: "流失中", value: 6 }
			],
			// 表格配置
			// 表格配置
			table: {
				"context-menu": ["refresh"],
				columns: [
					{ label: "预约时间", prop: "appoint_date", width: 150 },
					{
						label: "客户信息",
						prop: "customer",
						minWidth: 210,
						align: "left",
						showOverflowTooltip: true
					},
					{ label: "预约类型", prop: "cus_type_dec", width: 100 },
					{
						label: "预约门店",
						prop: "dept_name",
						minWidth: 150,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "客服到店",
						prop: "order_arrived",
						minWidth: 240,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "预约备注",
						prop: "remarks",
						minWidth: 240,
						align: "left",
						showOverflowTooltip: true,
						formatter: row => row.remarks || "-"
					},

					{
						label: "所属事业部",
						prop: "biz_name",
						minWidth: 150,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "分公司",
						prop: "company_name",
						minWidth: 150,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "品牌",
						prop: "bra_name",
						minWidth: 150,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "预约人员",
						prop: "add_user_name",
						minWidth: 100,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "排店人员",
						prop: "order_date_id_name",
						minWidth: 100,
						align: "left",
						showOverflowTooltip: true
					},
					{ label: "预约状态", prop: "status", width: 100 },
					{ label: "操作", prop: "opt", width: 250, fixed: "right" }
				]
			},
			userList: [],
			deptList: [],
			preDeptList: [],
			search: {
				search_content: "",
				biz_id: "",
				company_id: "",
				bra_id: [],
				dept_id: [], //所属
				city_id: "",
				after_dept_id: [],
				order_date_id_user: "",
				status: 1,
				appoint_date: [dayjs().format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")],
				search_type: 6,
				is_undetermined: 2,
				cus_type: 0,
				user_id: "",
				appoint_dept_id: [],
				keyword_type: 4
			},
			financeData: [],
			afterDeptList: [],
			afterUserList: [],
			cityList: []
		};
	},
	computed: {
		...mapState("common", ["visibleCusDetail", "visibleAppointForm", "cusFormSubmit"]),
		bizRefData() {
			const { biz_id } = this.search;
			return this.getBizRefData(biz_id);
		}
	},
	watch: {
		visibleCusDetail(v) {
			!v && this.refresh(false);
		},
		visibleAppointForm(v) {
			!v && this.refresh(false);
		},
		cusFormSubmit(v) {
			v && this.refresh();
		}
	},
	created() {
		this.search.biz_id = this.getCurrBiz();
		this.getAfterDept();
		// this.search.bra_id = this.bizList[0]?.brand[0]?.bra_id
		// this.search.company_id = this.bizList[0]?.company[0]?.company_id

		this.init().done(() => {
			const { company, brand } = this.bizRefData;
			// this.search.company_id = company[0]?.company_id ?? "";
			// this.search.bra_id = brand.length > 0 ? [brand[0]?.bra_id] : [];

			this.refresh(false);
		});
		this.getCityList();
	},
	methods: {
		updateKeyword(e) {
			this.search.search_content = e.search_content.trim();
			this.search.keyword_type = e.keyword_type;
		},

		async getCityList() {
			const { biz_id } = this.search;
			this.$service.spread.getbizcity({ biz_id }).then(data => {
				let list = (data || []).map(v => ({ ...v, label: v.name, value: v.id }));
				this.cityList = list;
			});
		},
		async exportExcel() {
			// exportExcel('#appointTable')
			const loading = this.$loading({
				lock: true,
				text: "正在导出~"
			});
			const query = {
				...this.search,
				all_page: 1
			};
			const { list } = await this.$service.cart.page(query).catch(e => {
				loading.close();
				throw e;
			});

			if (list?.length > 0) {
				const newList = list.map(row => {
					let status =
						row.status == 5 && row.appoint_date != "-"
							? "已超时"
							: constFilterFn(row.status, "APPIONT_TYPE");
					return {
						...row,
						customer: `${row.cus_name}(手机号:${row.cus_mobile};微信号:${row.cus_wx})`,
						status
					};
				});
				let columns = cloneDeep([...this.table.columns]);
				columns.pop();
				exportExcelCoustom("预约" + dayjs().format("YYYYMMDDhhmmss"), newList, columns);
			}
			loading.close();
		},
		async init() {
			const { biz_id } = this.search;
			this.getPreDept();
			return Promise.all([this.updateBizRefData(biz_id), this.initData()]);
		},
		async initData() {
			const { biz_id } = this.search;
			return Promise.all([
				delEmptyChildren(
					(this.deptList = await this.$store.dispatch("common/getDept", {
						biz_id,
						needAll: false,
						needCascader: true,
						type: 1
					}))
				),
				this.getUserList()
			]);
		},
		async getAfterDept() {
			const { biz_id } = this.search;
			this.afterDeptList = delEmptyChildren(
				(await this.$store.dispatch("common/getDept", {
					biz_id,
					post: 2,
					needAll: false,
					needCascader: true
				})) || []
			);
			console.log("this.afterDeptList", this.afterDeptList);
		},
		async getPreDept() {
			const { biz_id } = this.search;
			this.preDeptList = await this.$service.dept.preDept({
				parent_id: 0,
				biz_id
			});
		},
        async onRefresh(params, { next, render, done }) {
			// if (!params.bra_id.length) {
			// 	this.$message.error("请选择品牌");
			// 	return done();
			// }
			if(params.search_content&&params.search_content.length < 2){
				this.$message.error("使用关键字搜索时中文至少2位查询，其他至少4位可查询");
				return done();
			}
        
			// this.loading = true;
			const { data } = await next(params)
			// console.log(data)
			// render(data);
		},
		onLoad({ ctx, app }) {
			ctx.service(this.$service.cart).done();
		},
		// crud刷新
		refresh(reset = true) {
			let params = { ...this.search };
			if (reset) {
				params.page = 1;
			}
			this.$refs.crud.refresh(params);
			this.$nextTick(() => {
				this.$refs.table?.calcMaxHeight?.();
			});
		},
		openDetail(row) {
			this.$layout.openCusDetail(row, "new-appoint");
		},
		changeBiz(v) {
			this.search = {
				...this.search,
				company_id: "",
				bra_id: [],
				dept_id: [],
				after_dept_id: [],
				order_date_id_user: "",
				city_id: "",
				add_user_name: "",
				user_id: "",
				appoint_dept_id: []
			};
			// this.refresh();
			this.init();
			this.getAfterDept();
			this.getCityList();
		},
		changeAppointDept() {
			this.search.user_id = "";
			this.getUserList();
			this.refresh();
		},
		//人员
		async getUserList() {
			const { biz_id, appoint_dept_id } = this.search;
			this.userList = [];
			if (!biz_id) return;
			const data = await this.$service.user.deptuserlists({
				biz_id,
				dept_id: last(appoint_dept_id)
			});
			this.userList = data;
		},
		changeDept() {
			this.search.order_date_id_user = "";
			this.getManageDeptUser();
		},
		// 获取排店人员
		async getManageDeptUser() {
			const { after_dept_id, biz_id } = this.search;
			// if (Array.isArray(dept_id)) {
			// 	dept_id = dept_id.join();
			// }
			this.afterUserList = [];
			const data = await this.$service.user.deptuserlists({
				biz_id,
				dept_id: after_dept_id[1],
				post: 2
			});
			this.afterUserList = data;
		},
		// 打开预约
		openAppoint(row) {
			this.$refs.modifyCartTime.open(row);
			// this.$refs.form.open(row);
		},
		openAppointBoard(data) {
			const { biz_id, dept_id, ...args } = this.search;
			let params = {
				// ...args,
				biz_id: data.biz_id || biz_id
				// dept_id: data.dept_id
			};

			this.$layout.openAppointBoard(params);
		},
		// *********** 给财务导数据使用 start 暂不删除 ***********
		async startTask() {
			let data = [];
			for (let i = 1; i < 20; i++) {
				const rtData = await this.getFinanceData(i);
				data = [...data, ...rtData];
			}

			this.financeData = data.map(e => {
				return {
					...e,
					customer: `${e.cus_name}${e.cus_mobile}${e.cus_wx}`,
					status: constFilterFn(e.status, "APPIONT_TYPE")
				};
			});

			console.info("data11233**************************", this.financeData);
		},
		async getFinanceData(page) {
			const { list } = await this.$service.cart.page({
				...this.search,
				page: page,
				size: 3000
			});
			return list;
		},
		async exportFinanceExcel() {
			await this.startTask();
			exportExcelCoustom("当月预约数据", this.financeData, this.table.columns);
		},
		async arrived(item) {
			await this.$service.cart.arrived({cart_id: item.cart_id})
			this.$message.success('操作成功')
			this.refresh(false);
		}
		// *********** 给财务导数据 end ***********
	}
};
</script>

<style lang="scss" scoped>
.is-pending {
	color: $primary;
	font-weight: bold;
}

</style>
